package com.itany.shop.controller;

import com.itany.shop.dao.ItemDao;
import com.itany.shop.entity.Item;
import com.itany.shop.entity.Order;
import com.itany.shop.entity.Product;
import com.itany.shop.entity.User;
import com.itany.shop.exception.*;
import com.itany.shop.factory.ObjectFactory;
//import com.itany.shop.service.OrderService;
import com.itany.shop.service.CartService;
import com.itany.shop.service.OrderService;
import com.itany.shop.service.ProductService;
import com.itany.shop.service.UserService;
import com.itany.shop.vo.Cart;

import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class MainController {
    private ProductService productService = (ProductService) ObjectFactory.getObject("productService");
    private UserService userService = (UserService) ObjectFactory.getObject("userService");
    private CartService cartService = (CartService) ObjectFactory.getObject("cartService");
    private OrderService orderService = (OrderService) ObjectFactory.getObject("orderService");
    private Scanner sc = new Scanner(System.in);
    private User user;
    // 当用户成功登录之后,会创建一个当前类的对象
    // 每次创建对象后在该对象的属性中都会创建一个购物车对象
    // 用于表示分配个体当前登录的用户的购物车
    private com.itany.shop.vo.Cart cart = new com.itany.shop.vo.Cart();

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public com.itany.shop.vo.Cart getCart() {
        return cart;
    }

    public void setCart(com.itany.shop.vo.Cart cart) {
        this.cart = cart;
    }

    public MainController(User user) {
        this.user = user;
    }
    public void showMenu() {
        System.out.println("*********************欢迎"+user.getUsername()+"成功进入紫金商城主页*********************");
        System.out.print("请选择服务(1.加入购物车 2.查看购物车 3.我的订单 4.修改密码 5.退出登录):");
        int choice = sc.nextInt();
        switch (choice) {
            case 1:
                addCart();
                break;
            case 2:
                showCart();
                break;
            case 3:
                findMyOrders();
                break;
            case 4:
                modifyPassword();
                break;
            case 5:
                System.out.println("提示:您已经退出登录!");
                new StartController().showMenu();
                break;
            default:
                System.out.println("错误:对不起,您输入的选项有误,请重新输入");
                break;
        }
    }


    //加入购物车缓存
    public void addCart() {
        //加入前先查询所有商品
        List<Product> products = productService.findAll();
        System.out.println("*********************商品列表*********************");
        System.out.println("ID\t商品名称\t价格");
        for (Product product : products) {
            System.out.println(product.getId() + "\t" + product.getName() + "\t" + product.getPrice());
        }
        System.out.print("请输入要加入购物车的商品ID:");
        String id = sc.next();
        System.out.print("请输入购买数量:");
        int num = sc.nextInt();
        try {
            cartService.addCart(cart,id,num);
            System.out.println("加入购物车成功");
            showMenu();
        } catch (UserNotLoginException e) {
            System.out.println("错误:"+e.getMessage());//未登录异常
            new StartController().showMenu();
        } catch (RequestParameterErrorException e) {
            System.out.println("错误:"+e.getMessage());
            showMenu();
        }
    }



    public void showCart() {
        // 查看购物车业务功能
        List<Item> items = cart.getItems();
        double totalPrice = 0.0;
        System.out.println("商品编号\t\t商品名称\t\t商品单价\t\t商品数量\t\t商品总价");
        //此处购物车为一个缓存，因此直接查询购物车通过遍历查询购物车的东西，
        for (Item item : items) {
            Product p = item.getProduct();
            System.out.println(p.getId() + "\t\t" + p.getName() + "\t\t" + p.getPrice() + "\t\t" + item.getNum() + "\t\t" + (p.getPrice() * item.getNum()));
        }
        System.out.println("---------------------------------------------------------------------------------");
        System.out.println("当前购物车总金额为:" + cart.getPrice());
        // 二级菜单
        System.out.print("请选择服务(1.删除指定商品 2.修改商品数量 3.清空购物车 4.结算 5.回到主菜单):");
        int choice = sc.nextInt();
        switch (choice){
            case 1:
                deleteCartItem();
                break;
            case 2:
                updateCartItemNum();
                break;
            case 3:
                clearCart();
                break;
            case 4:
                settleCart();
                break;
            case 5:
                showMenu();
                return;
            default:
                System.out.println("输入有误，请重新选择！");
        }
        showCart();
    }

    // 删除指定商品
    private void deleteCartItem() {
        System.out.print("请输入要删除的商品ID：");
        String id = sc.next();
        try {
            cartService.removeCart(cart, id);
            System.out.println("提示:恭喜您,删除成功");
        } catch (UserNotLoginException e) {
            System.out.println("错误:" + e.getMessage());
            new StartController().showMenu();
        } catch (RequestParameterErrorException e) {
            System.out.println("错误:" + e.getMessage());
            showMenu();
        }

    }

    // 修改商品数量并重新计算总价
    private void updateCartItemNum() {
        System.out.print("请输入要修改的商品ID：");
        String id = sc.next();
        System.out.print("请输入新的数量：");
        int newNum = sc.nextInt();
        try {
            cartService.updateCart(cart,id,newNum);
            System.out.println("提示，恭喜你，修改成功");
        } catch (UserNotLoginException e) {
            System.out.println("错误:" + e.getMessage());
            new StartController().showMenu();
        } catch (RequestParameterErrorException e) {
            System.out.println("错误:" + e.getMessage());
            showMenu();
        }
    }

    // 清空购物车
    private void clearCart() {
        cart=new Cart();
        System.out.println("购物车已清空！");
    }

    // 结算购物车
    private void settleCart() {
        try {
            String no = orderService.createNo(cart, user);
            System.out.println("提示:恭喜您,结算成功,您的订单号为:" + no);
            // 结算成功之后需要清空购物车
            cart = new Cart();
        } catch (UserNotLoginException e) {
            System.out.println("错误:" + e.getMessage());
            new StartController().showMenu();
        }
        showMenu();

    }

    public void findMyOrders() {

        // 展示属于当前登录的用户的所有订单信息
        try {
            // 调用订单服务查询当前用户的订单列表
            List<Order> orders = orderService.findOrderIdsAndNosByUserId(user.getId());
            // 展示订单列表
            System.out.println("*********************我的订单*********************");
            System.out.println("订单ID\t\t订单号\t\t总价");
            for (Order order : orders) {
                System.out.println(order.getId() + "\t\t" + order.getNo()+"\t\t"+order.getPrice());
            }
        } catch (ServiceException e) {
            System.out.println("错误:查询订单失败，" + e.getMessage());
        }
        // 存在二级菜单
        System.out.print("请选择服务(1.查看订单详情 2.返回主菜单):");
        int choice = sc.nextInt();
        switch (choice) {
            case 1:
                findOrderDetail();
                break;
            case 2:
                showMenu();
                break;
        }showMenu();
    }
    public void findOrderDetail() {
//        用户名:xxx
//        手机号:xxxxx
//        订单号:xxxxxxxxxx
//        -------------------------------------------
//        序号	商品名称	数量	总价
//        1
//        2
//        3
//        4
//        ----------------------------------------------
//        共:xxx元 总计:4条

    }

    public void modifyPassword() {
        System.out.print("请输入旧密码：");
        String oldPassword = sc.next();
        System.out.print("请输入新密码：");
        String newPassword = sc.next();
        try {
            userService.updatePassword(user.getId(), oldPassword, newPassword);
            System.out.println("提示：密码修改成功，请重新登录");
            System.out.println("提示：您已经退出登录!");
            new StartController().showMenu();
        } catch (RequestParameterErrorException e) {
            System.out.println("错误：" + e.getMessage());
            showMenu();
        } catch (PasswordErrorException e) {
            System.out.println("错误：" + e.getMessage());
            showMenu();
        }
        showMenu();
    }
}
